package com.rainng.coursesystem.module.plan.service.impl;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rainng.coursesystem.base.api.dto.PagingReqDTO;
import com.rainng.coursesystem.config.docx.bookTagConfig;
import com.rainng.coursesystem.model.vo.response.ResultVO;
import com.rainng.coursesystem.module.plan.dto.baseEntity.testRecordItemEntity;
import com.rainng.coursesystem.module.plan.dto.baseEntity.testReportDataBaseEntity;
import com.rainng.coursesystem.module.plan.dto.baseEntity.testReportItemEntity;
import com.rainng.coursesystem.module.plan.dto.baseEntity.testReportParamEntity;
import com.rainng.coursesystem.module.plan.dto.entity.*;
import com.rainng.coursesystem.module.plan.dto.request.*;
import com.rainng.coursesystem.module.plan.dto.response.testReportDataRes;
import com.rainng.coursesystem.module.plan.mapper.PlanInsMapper;
import com.rainng.coursesystem.module.plan.mapper.assistMapper;
import com.rainng.coursesystem.module.plan.service.SaveInsectionService;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.BookmarksNavigator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.wml.Text;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.rainng.coursesystem.util.docReplace.getAllElementFromObject;
import static com.rainng.coursesystem.util.docReplace.searchAndReplace;
import static com.rainng.coursesystem.util.docxUtil.getValueByDocxTag;
import static com.rainng.coursesystem.util.serializaUtil.List2Str;
import static com.rainng.coursesystem.util.serializaUtil.Str2List;
//import static com.rainng.coursesystem.util.wpsDocx.getValueByDocxTag;

@Slf4j
@Service
public class SaveInsectionServiceImpl extends ServiceImpl<PlanInsMapper, PlanToInsepection> implements SaveInsectionService {

    @Value("${template.recordTemplatePath}")
    private String recordTemplatePath;

    @Value("${template.recordDocxPath}")
    private String recordDocxPath;

    @Value("${template.reportTemplatePath}")
    private String reportTemplatePath;

    @Value("${template.reportDocxPath}")
    private String reportDocxPath;


    @Autowired
    private bookTagConfig bookConfig;


    @Autowired
    private assistMapper mapper;
    private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("\\$\\{.*?\\}");
    private static final Pattern PLACEHOLDER_PATTERN2 = Pattern.compile("\\\\");


    @Override
    public Integer insertPhotoData(photoResultEntity photo) {
        Integer result=baseMapper.insertPhotoData(photo);
        return result;
    }

    public ResultVO updateStatus(PlanStatusDto plan) {
        baseMapper.updateStatus(plan);
        return new ResultVO<>(ResultVO.SUCCESS, "确认成功",null);
    }

    @Override
    public ResultVO saveTestTemplate(testTempateEntity tempInfo) {
        Integer count= mapper.getrecTempCount(tempInfo.getVeType(), tempInfo.getPrjNum());
        if(count==0){
            Integer result=baseMapper.insertTestTemplate(tempInfo);

            return new ResultVO<>(ResultVO.SUCCESS, "success",null);
        }
        else{
            return new ResultVO<>(201,"添加失败，当前该汽车类型以及项目下已经存在模板了！",null);
        }
    }
    @Override
    public ResultVO saveReportTemplate(testReportTemplateEntity tempInfo) {
        testReportTemplateEntity initialTemp=mapper.getrepTemp(tempInfo.getVeType(),tempInfo.getPrjNum());
        if(initialTemp==null){
            Integer result=baseMapper.insertReportTemplateData(tempInfo);
            return new ResultVO<>(ResultVO.SUCCESS, "success",null);
        }
        else{
            return new ResultVO<>(201,"添加失败，当前该汽车类型以及项目下已经存在模板了！",null);
        }
    }

    @Override
    public Integer updateTestTemplate(testTempateEntity tempInfo) throws InvocationTargetException, IllegalAccessException {
//        testTempateEntity temp=new testTempateEntity();
//        BeanUtils.copyProperties(temp,tempInfo);
//        temp.setParamInfo(List2Str(tempInfo.getParamList()));
        Integer res= mapper.updateTestTemplate(tempInfo);
        return res;
    }
    @Override
    public Integer updateReportTemplate(testReportTemplateEntity tempInfo) throws InvocationTargetException, IllegalAccessException {
        testReportTemplateEntity temp=new testReportTemplateEntity();
//        BeanUtils.copyProperties(temp,tempInfo);
//        temp.setParamInfo(List2Str(tempInfo.getParamList()));
        Integer res=mapper.updateReportTemplate(tempInfo);
        return res;
    }


    @Override
    public IPage<testTempateEntity> paging(PagingReqDTO<testTemplateReqDto> reqDTO) {
//            IPage<testTemplateReqDto> res = new Page<>();
//            List<testTemplateReqDto> testList=new ArrayList<>();
        IPage<testTempateEntity> res1 = null;
        res1 = baseMapper.paging(reqDTO.toPage(), reqDTO.getParams());
//            List<testTempateEntity> list=res1.getRecords();
//            for(testTempateEntity o: list){
//                testTemplateReqDto newTemp=new testTemplateReqDto();
//                newTemp.setVeType(o.getVeType());
//                newTemp.setId(o.getId());
//                newTemp.setCreateTime(o.getCreateTime());
//                newTemp.setCreateUser(o.getCreateUser());
//                newTemp.setTireCode(o.getTireCode());
//                newTemp.setPrjNum(o.getPrjNum());
//                newTemp.setPrjName(o.getPrjName());
//                List<testRecordParamEntity> gf= Str2List(o.getParamInfo(),testRecordParamEntity.class);
//                newTemp.setParamList(gf);
//                testList.add(newTemp);
//            }
//            res.setRecords(testList);
//            res.setCurrent(res1.getCurrent());
//            res.setSize(res1.getSize());
//            res.setPages(res1.getPages());
//            res.setTotal(res1.getTotal());
        return res1;
    }

    @Override
    public IPage<photoResultEntity> photopaging(PagingReqDTO<photoDataReqDto> reqDTO) {
        IPage<photoResultEntity> res = null;
        res = baseMapper.photopaging(reqDTO.toPage(), reqDTO.getParams());
        return res;
    }

    @Override
    public IPage<taskAssignEntity> assignpaging(PagingReqDTO<taskAssignReqDto> reqDTO) {
        IPage<taskAssignEntity> res = null;
        res = baseMapper.assignpaging(reqDTO.toPage(), reqDTO.getParams());
        return res;
    }

    @Override
    public Integer inserttestRecordData(testDataReqDto record) throws Docx4JException, IOException {
        testRecordDataEntity et=new testRecordDataEntity();
        et.setRecordDataStr(List2Str(record.getRecordList()));
        et.setAssignId(record.getAssignId());
        et.setPrjNum(record.getPrjNum());
        et.setTire(record.getTire());
        et.setVin(record.getVin());
        et.setCreateTime(record.getCreateTime());
        et.setCreateUser(record.getCreateUser());
        et.setVeType(record.getVeType());
        et.setPrjName(record.getPrjName());
        Integer result=baseMapper.insertTestRecordData(et);
        //将文件数据写入docx文档,获取实验模板
        List<testTempateEntity> temp=mapper.getrecTemp(record.getVeType(),record.getPrjNum());
        if(temp.size()>0){
            Integer id=et.getId();
            String docxTemplateName=temp.get(0).getDocxTemplateName();
            //文件名字段
            String docxFileName=this.TestDataTransToDocx(docxTemplateName,et);
            //新增成功，则把问文件报告写入实验记录数据报告信息更新到数据库表字段里面
            Integer res=mapper.updatedocxFileName(id,docxFileName);
        }
        return result;
    }

    /**
     * 补偿实测记录数据文档
     * @param record
     * @return
     */

    @Override
    public Integer generateRecordDocx(testRecordDataEntity record) throws IOException, Docx4JException {
        //将文件数据写入docx文档,获取实验模板
        List<testTempateEntity> temp=mapper.getrecTemp(record.getVeType(),record.getPrjNum());
        if(temp.size()>0){
            Integer id=record.getId();
            String docxTemplateName=temp.get(0).getDocxTemplateName();
            //文件名字段
            String docxFileName=this.TestDataTransToDocx(docxTemplateName,record);
            //当模板库存在
            if(docxFileName!=null && docxFileName!=""){
                return 1;
            }
        }
        return 0;
    }

    @Override
    public Integer generateReportDocx(testReportDataEntity report) throws IOException, Docx4JException {
        //将文件数据写入docx文档,获取实验模板
        List<testReportTemplateEntity> temp=mapper.getreportTemp(report.getRecordDataId());
        if(temp.size()>0){
            String docxTemplateName=temp.get(0).getDocxTemplateName();
            //文件名字段
            String docxFileName=this.reportDataTransToDocx(docxTemplateName,report);
            //当模板库存在
            if(docxFileName!=null && docxFileName!=""){
                return 1;
            }
        }
        return 0;
    }



    /**
     * 保存转换好的实验记录文件
     * @param docxTemplateName
     * @param recordData
     * @param
     * @return
     * @throws Docx4JException
     */
    public String TestDataTransToDocx(String docxTemplateName,testRecordDataEntity recordData) throws Docx4JException, IOException {
        //找到实验记录文件模板
        String docxTemplateFile = recordTemplatePath + docxTemplateName;
        //判断当前是否存在该文件模板
        File file=new File(docxTemplateFile);
        if(file.exists()){
            String vin=recordData.getVin();
            Integer id=recordData.getId();
            //定义转换后的实验记录文件，由VIN码确定唯一值
            String docxFileName=vin + "_" + id + "_" + docxTemplateName;
            //定义转换后的文件位置
            String docxFilePath = recordDocxPath + docxFileName;
            List<testRecordItemEntity> gf= Str2List(recordData.getRecordDataStr(), testRecordItemEntity.class);
            updataDocxDataByBookTag(docxTemplateFile,docxFilePath,gf);
            return docxFileName;
        }
        return null;
    }

    // 更换实验报告数据字符串
    public void updataReportDocxDataByBookTag(String docxTemplateFile,String docxFilePath, List<testReportItemEntity> gf,Map<String,String> carmap) {
        Document document = new Document();
        document.loadFromFile(docxTemplateFile);
        //定位到书签
        BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);
        //将用户填写的数据转换到docx文档
        for(testReportItemEntity item: gf){
            String type=item.getParamType();
            if(type.equals("0")){
                //移除
                String holder=item.getPlaceholder();
                if(item.getValue()!=null && item.getValue().length()!=0){
                    bookmarkNavigator.moveToBookmark(holder);
                    bookmarkNavigator.replaceBookmarkContent(item.getValue(), false);
                }

            }
            else if(type.equals("1")){
                String[] placeholderArray=item.getPlaceholder().split(";");
                //首先将该选项下所有书签初始化成方框
                for(String pl: placeholderArray){
                    //移除
                    bookmarkNavigator.moveToBookmark(pl);
                    bookmarkNavigator.replaceBookmarkContent(" □ ", false);
                }
                //找到需要替换成方框打勾的选项
                String value=item.getValue();
                String[] optionsArray=item.getParamOptions().split(";");
                //获取用户所填写的值在选项里面的index位置，替换成方框打勾
                int index = Arrays.asList(optionsArray).indexOf(value);
                if(index!=-1){
                    bookmarkNavigator.moveToBookmark(placeholderArray[index]);
                    bookmarkNavigator.replaceBookmarkContent(" ☑ ", false);
                }
            }
        }
        //将固定数据传递Docx文档
        if(carmap!=null){
            //Lambda表达式
            carmap.forEach((k,v) ->{
                bookmarkNavigator.moveToBookmark(k);
                bookmarkNavigator.replaceBookmarkContent(v, false);

            });
        }
        document.saveToFile(docxFilePath, FileFormat.Docx_2013);
        document.dispose();
    }


    //更换实验记录数据字符串
    public void updataDocxDataByBookTag(String docxTemplateFile,String docxFilePath, List<testRecordItemEntity> gf) {

        Document document = new Document();
        document.loadFromFile(docxTemplateFile);
        //定位到书签
        BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);

        for(testRecordItemEntity item: gf){
            String type=item.getType();
            if(type.equals("0")){
                //移除
                String holder=item.getPlaceholder();
                if(item.getValue()!=null && item.getValue().length()!=0){
                    bookmarkNavigator.moveToBookmark(holder);
                    bookmarkNavigator.replaceBookmarkContent(item.getValue(), false);
                }

            }
            else if(type.equals("1")){
                String[] placeholderArray=item.getPlaceholder().split(";");
                //首先将该选项下所有书签初始化成方框
                for(String pl: placeholderArray){
                    //移除
                    bookmarkNavigator.moveToBookmark(pl);
                    bookmarkNavigator.replaceBookmarkContent(" □ ", false);
                }
                //找到需要替换成方框打勾的选项
                String value=item.getValue();
                String[] optionsArray=item.getParamOptions().split(";");
                //获取用户所填写的值在选项里面的index位置，替换成方框打勾
                int index = Arrays.asList(optionsArray).indexOf(value);
                if(index!=-1){
                    bookmarkNavigator.moveToBookmark(placeholderArray[index]);
                    bookmarkNavigator.replaceBookmarkContent(" ☑ ", false);
                }
            }
        }
        document.saveToFile(docxFilePath, FileFormat.Docx_2013);
        document.dispose();
    }



    private void postRecordDocx(String path) throws IOException {

        FileInputStream fis = new FileInputStream(path);
        XWPFDocument document = new XWPFDocument(fis);
        fis.close();

//        removePlaceholders(document);

        List<XWPFTable> tables = document.getTables();
        for (XWPFTable table : tables) {
            for (XWPFTableRow row : table.getRows()) {
                for (XWPFTableCell cell : row.getTableCells()) {
                    String text = cell.getText();
                    String replacedText = PLACEHOLDER_PATTERN.matcher(text).replaceAll("");
                    String replacedText1 = PLACEHOLDER_PATTERN2.matcher(replacedText).replaceAll("");
                    cell.removeParagraph(0); // Remove all paragraphs in the cell
                    cell.setText(replacedText1); // Set the new content
                }
            }
        }

        FileOutputStream fos = new FileOutputStream(path);
        document.write(fos);
        fos.close();
    }

    @Override
    public Integer TestDataToDocx(Integer id) throws Docx4JException {
        //文件转换符操作载体初始化
        String docxFile = "D:/test.docx";
        WordprocessingMLPackage template = WordprocessingMLPackage.load(new File(docxFile));
        List<Object> texts = getAllElementFromObject(
                template.getMainDocumentPart(), Text.class);
        //从数据库查出要生成报告的数据
        testRecordDataEntity recordData=mapper.getRecordData(id);
        List<testRecordItemEntity> gf= Str2List(recordData.getRecordDataStr(), testRecordItemEntity.class);
        Map<String, String> map = new HashMap<>();
        for(testRecordItemEntity item: gf){
            map.put(item.getPlaceholder(),item.getValue());
        }
        searchAndReplace(texts, map);
        template.save(new File("D:/tesw33333wt.docx"));

        return null;
    }


    /**
     * 将数据库字段转换成实体字段
     * @param reqDTO
     * @return
     */
    @Override
    public IPage<testDataReqDto> recordpaging(PagingReqDTO<testDataReqDto> reqDTO) {
        IPage<testDataReqDto> res = new Page<>();
        List<testDataReqDto> testList=new ArrayList<>();
        IPage<testRecordDataEntity> data = null;
        data = baseMapper.recorddatapaging(reqDTO.toPage(), reqDTO.getParams());
        List<testRecordDataEntity> list=data.getRecords();
        for(testRecordDataEntity o: list){
            testDataReqDto newTemp=new testDataReqDto();
            newTemp.setId(o.getId());
            newTemp.setVeType(o.getVeType());
            newTemp.setCreateTime(o.getCreateTime());
            newTemp.setCreateUser(o.getCreateUser());
            newTemp.setTire(o.getTire());
            newTemp.setPrjNum(o.getPrjNum());
            newTemp.setAssignId(o.getAssignId());
            newTemp.setVin(o.getVin());
            newTemp.setDocxFileName(o.getDocxFileName());
            newTemp.setPrjName(o.getPrjName());
            List<testRecordItemEntity> gf= Str2List(o.getRecordDataStr(), testRecordItemEntity.class);
            newTemp.setRecordList(gf);
            testList.add(newTemp);
        }
        res.setRecords(testList);
        res.setCurrent(data.getCurrent());
        res.setSize(data.getSize());
        res.setPages(data.getPages());
        res.setTotal(data.getTotal());
        return res;
    }

    @Override
    public IPage<testReportTemplateEntity> reportpaging(PagingReqDTO<testReportTemplateReqDto> reqDTO) {
        IPage<testReportTemplateEntity> res1 = null;
        res1 = baseMapper.reportpaging(reqDTO.toPage(), reqDTO.getParams());
        return res1;
    }

    /**
     * 根据试验报告模板以及实测记录生成试验报告
     * @param recordDataId
     * @return
     */

    @Override
    public Integer generateReportData(Integer recordDataId,String createUser,String createTime) throws IOException, Docx4JException {
        testRecordDataEntity recordData=mapper.getRecordData(recordDataId);
        testReportTemplateEntity reportTemp=mapper.getrepTemp(recordData.getVeType(),recordData.getPrjNum());
        if(reportTemp!=null){
            //试验报告整体数据
            testReportDataEntity data=new testReportDataEntity();
            //试验记录数据列表
            List<testRecordItemEntity> recordList= Str2List(recordData.getRecordDataStr(), testRecordItemEntity.class);
            //试验报告参数模板数据
            List<testReportParamEntity> gf= JSONArray.parseArray(reportTemp.getParamInfo(),testReportParamEntity.class);
            //试验报告具体项目数据
            List<testReportItemEntity> ItemList=new ArrayList<>();
            for (testReportParamEntity re: gf){
                testReportItemEntity itemData=new testReportItemEntity();
                try {
                    BeanUtils.copyProperties(itemData,re);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
                //0代表从试验记录到试验报告平均值计算
                if(re.getCompuLogicCode().equals("0")){
                    //如果由文本转换成int失败，则填空继续
                    try{
                        Double average = recordList.stream().filter(s->s.getParamGroupCode().equals(re.getParamGroupCode())).mapToDouble(item->Double.valueOf(item.getValue())).average().orElse(0);
                        itemData.setValue(average.toString());
                    }catch (NumberFormatException ex){
                        itemData.setValue("");
                    }
                }
                //1代表从试验记录到试验报告原值计算
                if(re.getCompuLogicCode().equals("1")){
                    List<testRecordItemEntity> recordTemp=recordList.stream().filter(s->s.getParamGroupCode().equals(re.getParamGroupCode())).collect(Collectors.toList());
                    if(recordTemp.size()>0){
                        itemData.setValue(recordTemp.get(0).getValue());
                    }
                    else{
                        itemData.setValue("");
                    }
                }
                ItemList.add(itemData);
            }
            String reportDa= List2Str(ItemList);
            data.setVin(recordData.getVin());
            data.setRecordDataId(recordDataId);
            data.setReportDataStr(reportDa);
            data.setCreateTime(createTime);
            data.setCreateUser(createUser);
            Integer res=baseMapper.insertReportData(data);
            String id=data.getId();
            String docxTemplateName= reportTemp.getDocxTemplateName();
            if(docxTemplateName!=null&&docxTemplateName.length()!=0){
                String docx_file_name=reportDataTransToDocx(docxTemplateName,data);
                //将保存成功后的文档名称记录更新到数据库
                if(docx_file_name!=null){
                    mapper.updaterepodocxFileName(id,docx_file_name);
                }

            }
            return res;
        }
        else{
            return 0;
        }
    }



    public String reportDataTransToDocx(String docxTemplateName,testReportDataEntity reportData) throws Docx4JException, IOException {
        //找到实验记录文件模板
        String docxTemplateFile = reportTemplatePath + docxTemplateName;
        //判断当前是否存在该文件模板
        File file=new File(docxTemplateFile);
        if(file.exists()){
            String vin=reportData.getVin();
            String id=reportData.getId();
            //定义转换后的实验记录文件，由VIN码确定唯一值
            String docxFileName=vin + "_" + id + "_" + docxTemplateName;
            //定义转换后的文件位置
            String docxFilePath = reportDocxPath + docxFileName;
            List<testReportItemEntity> gf= Str2List(reportData.getReportDataStr(), testReportItemEntity.class);
            //首先获取该vin下车辆信息，将车辆固定数据通过标签也写进实验报告文档
            Map<String,String> map=getCarInfoMap(vin);
            updataReportDocxDataByBookTag(docxTemplateFile,docxFilePath,gf,map);
            return docxFileName;
        }
        return null;
    }


    /**
     * 根据汽车vin码获取车辆信息统一处理成map格式
     * @param vin
     * @return
     */
    public Map<String,String> getCarInfoMap(String vin){
        List<carInfoEntity> carlist=mapper.getCarInfoList(vin);
        if(carlist.size()>0){
            //统一格式后的map结构
            Map<String,String> carMap=new HashMap<>();
            carInfoEntity car=carlist.get(0);
            carMap.put("Vin",vin);
            carMap.put("Wx001",car.getWx001());
            carMap.put("Wx002",car.getWx002());
            String config=car.getConfig().trim();
            if(config.length()>0){
                JSONObject js=JSONObject.parseObject(config);
                JSONObject object= JSONObject.from(js.get("config"));
                List<String> bks=bookConfig.getBookTag();
                for(String item: bks){
                    try {
                        String ty=object.get(item).toString();
                        carMap.put(item,ty);
                    }catch (Exception ex){

                    }
                }

            }
           return carMap;

        }
        return null;
    }

    public Integer reportDataToDocx(Integer id) throws Docx4JException {
        //文件转换符操作载体初始化
        String docxFile = "D:/test.docx";
        WordprocessingMLPackage template = WordprocessingMLPackage.load(new File(docxFile));
        List<Object> texts = getAllElementFromObject(
                template.getMainDocumentPart(), Text.class);
        //从数据库查出要生成报告的数据
        testRecordDataEntity recordData=mapper.getRecordData(id);
        List<testRecordItemEntity> gf= Str2List(recordData.getRecordDataStr(), testRecordItemEntity.class);
        Map<String, String> map = new HashMap<>();
        for(testRecordItemEntity item: gf){
            map.put(item.getPlaceholder(),item.getValue());
        }
        searchAndReplace(texts, map);
        template.save(new File("D:/tesw33333wt.docx"));

        return null;
    }




    @Override
    public Integer deleteReportTemplate(Integer id) {
        Integer res=mapper.deleteReportTemplate(id);
        return res;
    }

    /**
     * 获取试验报告分页数据
     * @param reqDTO
     * @return
     */

    @Override
    public IPage<testReportDataRes> reportdatapaging(PagingReqDTO<testReportDataBaseEntity> reqDTO) {
        IPage<testReportDataRes> res = new Page<>();
        //报告数据初始化list
        List<testReportDataRes> testList=new ArrayList<>();
        IPage<testReportDataEntity> redfs = null;
        redfs = baseMapper.reportdatapaging(reqDTO.toPage(), reqDTO.getParams());
        List<testReportDataEntity> relist=redfs.getRecords();
        for(testReportDataEntity re: relist){
            //新建一个
            testReportDataRes reRes=new testReportDataRes();
            try {
                BeanUtils.copyProperties(reRes,re);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            //试验报告具体条目参数数据
            List<testReportItemEntity> gf= Str2List(re.getReportDataStr(), testReportItemEntity.class);
            reRes.setDataList(gf);
            testList.add(reRes);
        }
        res.setRecords(testList);
        res.setCurrent(redfs.getCurrent());
        res.setSize(redfs.getSize());
        res.setPages(redfs.getPages());
        res.setTotal(redfs.getTotal());
        return res;
    }

    @Override
    public Integer deleteTestTemplate(Integer id) {
        Integer res=mapper.deleteTestTemplate(id);
        return res;
    }

    @Override
    public Integer updateTestRecordDtata(testDataReqDto testDataReq) throws InvocationTargetException, IllegalAccessException {
        testRecordDataEntity testData=new testRecordDataEntity();
        BeanUtils.copyProperties(testData,testDataReq);
        testData.setRecordDataStr(List2Str(testDataReq.getRecordList()));
        Integer res=mapper.updateTestRecordDtata(testData);
        return res;
    }

    /**
     * 实验记录模板一键转成实验报告参数模板
     * @param veType
     * @param prjNum
     * @return
     */
    @Override
    public testTempateEntity reportTransform(String veType, String prjNum) throws InvocationTargetException, IllegalAccessException {
        List<testTempateEntity> list=mapper.getTestRecordDataInfo(veType,prjNum);
        //要返回的实验报告
        testTempateEntity reportTemp=new testTempateEntity();
        if(list!=null&&list.size()>0){
            testTempateEntity recordTemp=list.get(0);
            BeanUtils.copyProperties(reportTemp,recordTemp);
//            List<testRecordParamEntity> recordItemList=  Str2List(recordTemp.getParamInfo(), testRecordParamEntity.class);
//            List<testReportParamEntity> reportItemList= new ArrayList<>();
//            for(testRecordParamEntity rec: recordItemList){
//                testReportParamEntity rep=new testReportParamEntity();
//                BeanUtils.copyProperties(rep,rec);
//                rep.setCompuLogicCode("1");
//                reportItemList.add(rep);
//            }
//            reportTemp.setParamList(reportItemList);
        }
        return reportTemp;
    }

    @Override
    public testRecordDataEntity getRecordById(Integer id) {
        testRecordDataEntity records=mapper.getRecordData(id);
        return records;
    }

    @Override
    public testReportDataEntity getReportById(Integer id) {
        testReportDataEntity rt=mapper.getReportData(id);
        return rt;
    }

    @Override
    public Integer updataTestRecordByDocx(testRecordDataEntity records) {
//        testRecordDataEntity records=mapper.getRecordData(id);
        String docxFileName=records.getDocxFileName();
        String filePath=recordDocxPath + docxFileName;
        Document doc2 = new Document();
        doc2.loadFromFile(filePath);
        List<testRecordItemEntity> gf= Str2List(records.getRecordDataStr(), testRecordItemEntity.class);
        gf.stream().map(item->{
            //获取书签，去docx文档里面搜寻数据
            String placeholder=item.getPlaceholder();
            //区别是文本框还是选择框，处理逻辑不同
            String type=item.getType();
            //文本框
            if(type.equals("0")){
                String value=getValueByDocxTag(doc2,item.getPlaceholder()).trim();
                item.setValue(value);
            }
            //选择框
            else if(type.equals("1")){
                String[] placeholds=placeholder.split(";");
                for(String bookMarkName: placeholds){
                    String value=getValueByDocxTag(doc2,bookMarkName).trim();
                    if(value.equals("☑")){
                        int index = Arrays.asList(placeholds).indexOf(bookMarkName);
                        if(index!=-1){
                            String[] optionsArray=item.getParamOptions().split(";");
                            item.setValue(optionsArray[index]);
                        }
                    }
                }
            }
            return item;
        }).collect(Collectors.toList());
        Integer CC=mapper.updateTestRecord(records.getId(),List2Str(gf));
        return null;
    }
}
